<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const users = ref < Array < { uuid: string; username: string } >> ([])
const currentUser = ref < { uuid: string; username: string } | null > (null)
const messages = ref < Array < { content: string; timestamp: string; is_customer: boolean } >> ([])
const newMessage = ref('')
let ws: WebSocket | null = null

onMounted(async () => {
    if (!userStore.isCustomerService) {
        ElMessage.error('无权访问')
        router.push('/chat')
        return
    }

    loadUsers()
})

async function loadUsers() {
    try {
        const { data } = await axios.get('http://127.0.0.1:8000/api/chat_users/')
        users.value = data.users
    } catch (error) {
        ElMessage.error('获取用户列表失败')
    }
}

async function selectUser(user: { uuid: string; username: string }) {
    currentUser.value = user
    try {
        const { data } = await axios.get(`http://127.0.0.1:8000/api/chat/history/${user.uuid}/`)
        messages.value = data.messages
        initWebSocket(user.uuid)
    } catch (error) {
        ElMessage.error('获取聊天记录失败')
    }
}

function initWebSocket(userUuid: string) {
    ws?.close()
    ws = new WebSocket(`ws://127.0.0.1:8000/ws/chat/${userUuid}/`)

    ws.onmessage = (event) => {
        const data = JSON.parse(event.data)
        messages.value.push({
            content: data.message,
            timestamp: new Date().toISOString(),
            is_customer: data.is_customer
        })
    }
}

function sendMessage() {
    if (!newMessage.value.trim() || !currentUser.value) return

    ws?.send(JSON.stringify({
        message: newMessage.value,
        is_customer: true
    }))

    newMessage.value = ''
}

async function deleteChat() {
    if (!currentUser.value) return

    try {
        await ElMessageBox.confirm('确定要删除该用户的聊天记录吗？', '警告', {
            type: 'warning'
        })

        await axios.delete(`http://localhost:8000/api/delete_chat/${currentUser.value.uuid}/`)
        ElMessage.success('删除成功')
        messages.value = []
        currentUser.value = null
        loadUsers()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}
</script>

<template>
    <div class="customer-service">
        <div class="header">
            <h2>客服系统</h2>
            <el-button @click="router.push('/')">返回首页</el-button>
        </div>

        <div class="main-content">
            <div class="users-list">
                <h3>用户列表</h3>
                <el-menu :default-active="currentUser?.uuid"
                    @select="(uuid) => selectUser(users.find(u => u.uuid === uuid)!)">
                    <el-menu-item v-for="user in users" :key="user.uuid" :index="user.uuid">
                        {{ user.username }}
                    </el-menu-item>
                </el-menu>
            </div>

            <div class="chat-area" v-if="currentUser">
                <div class="chat-header">
                    <span>正在与 {{ currentUser.username }} 对话</span>
                    <el-button type="danger" @click="deleteChat">删除聊天记录</el-button>
                </div>

                <div class="messages">
                    <div v-for="(msg, index) in messages" :key="index"
                        :class="['message', msg.is_customer ? 'customer' : 'user']">
                        <div class="message-content">
                            {{ msg.content }}
                        </div>
                        <div class="message-time">
                            {{ new Date(msg.timestamp).toLocaleString() }}
                        </div>
                    </div>
                </div>

                <div class="input-area">
                    <el-input v-model="newMessage" placeholder="请输入回复内容" @keyup.enter="sendMessage">
                        <template #append>
                            <el-button @click="sendMessage">发送</el-button>
                        </template>
                    </el-input>
                </div>
            </div>

            <div class="no-chat" v-else>
                <el-empty description="请选择一个用户开始对话" />
            </div>
        </div>
    </div>
</template>

<style scoped>
.customer-service {
    height: 100vh;
    padding: 1rem;
    display: flex;
    flex-direction: column;

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }

    .main-content {
        flex: 1;
        display: flex;
        gap: 1rem;
        background: #f5f5f5;
        border-radius: 4px;
        padding: 1rem;
        height: calc(100vh - 100px);

        .users-list {
            width: 200px;
            background: white;
            border-radius: 4px;
            padding: 1rem;

            h3 {
                margin-bottom: 1rem;
            }
        }

        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: white;
            border-radius: 4px;
            padding: 1rem;

            .chat-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 1rem;
                padding-bottom: 1rem;
                border-bottom: 1px solid #eee;
            }

            .messages {
                flex: 1;
                overflow-y: auto;
                padding: 1rem;
                background: #f9f9f9;
                border-radius: 4px;
                margin-bottom: 1rem;

                .message {
                    margin-bottom: 1rem;
                    max-width: 70%;

                    &.user {
                        margin-right: auto;

                        .message-content {
                            background: #e1f3fc;
                        }
                    }

                    &.customer {
                        margin-left: auto;

                        .message-content {
                            background: #95ec69;
                        }
                    }

                    .message-content {
                        padding: 0.5rem 1rem;
                        border-radius: 4px;
                        word-break: break-word;
                    }

                    .message-time {
                        font-size: 0.8rem;
                        color: #999;
                        margin-top: 0.2rem;
                    }
                }
            }
        }

        .no-chat {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
            border-radius: 4px;
        }
    }
}
</style>